#include <cctype>
#include <regex>
#include <brpc/server.h>
#include <butil/logging.h>

#include "data_es.hpp"      // es数据管理封装
#include "mysql_chat_session_member.hpp"// mysql数据管理封装
#include "mysql_chat_session.hpp"       // mysql数据管理封装
#include "mysql_relation.hpp"           // mysql数据管理封装
#include "mysql_apply.hpp"              // mysql数据管理封装
#include "etcd.hpp"         // 服务注册封装
#include "logger.hpp"       // 日志模块封装
#include "channel.hpp"      // 信道管理模块
#include "utils.hpp"        // 基础工具接口

#include "base.pb.h"        // protobuf框架代码
#include "friend.pb.h"      // protobuf框架代码
#include "user.pb.h"        // protobuf框架代码
#include "message.pb.h"     // protobuf框架代码

namespace suye
{
class FriendServiceImpl : public suye::FriendService {
public:
    FriendServiceImpl(const std::shared_ptr<elasticlient::Client>& es_client,
        const std::shared_ptr<odb::core::database>& mysql_client,
        const ServiceManager::ptr& channel_manager,
        const std::string& user_service_name,
        const std::string& message_service_name) 
        : _es_user(std::make_shared<ESUser>(es_client))
        , _mysql_relation(std::make_shared<RelationTable>(mysql_client))
        , _mysql_apply(std::make_shared<FriendApplyTable>(mysql_client))
        , _mysql_chat_session(std::make_shared<ChatSessionTable>(mysql_client))
        , _mysql_chat_session_member(std::make_shared<ChatSessionMemberTable>(mysql_client))
        , _user_service_name(user_service_name)
        , _message_service_name(message_service_name)
        , _sm_channels(channel_manager) {}

    ~FriendServiceImpl() {}

    virtual void GetFriendList(::google::protobuf::RpcController* controller,
                       const ::suye::GetFriendListReq* request,
                       ::suye::GetFriendListRsp* response,
                       ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);

        auto err_response = [this, response](const std::string& rid, 
            const std::string& errmsg) -> void {
                response->set_request_id(rid);
                response->set_success(false);
                response->set_errmsg(errmsg);
                return;
            };

        // 1.获取请求中的用户ID
        std::string rid = request->request_id();
        std::string uid = request->user_id();

        // 2.根据用户ID，从数据库的好友关系表中取出该用户所有的好友ID
        auto friends_id_list = _mysql_relation->friends(uid);
        std::unordered_set<std::string> users_id_list;
        for (auto& id: friends_id_list) {
            users_id_list.insert(id);
        }

        // 3.根据好友ID，从用户子服务批量获取好友数据
        std::unordered_map<std::string, UserInfo> users_list;
        bool res = GetUserInfo(rid, users_id_list, users_list);
        if (res == false) {
            LOG_ERROR("{} - 批量获取用户信息失败!", rid);
            return err_response(rid, "批量获取用户信息失败!");
        }

        // 4.组织响应，将好友列表返回给网关
        response->set_request_id(rid);
        response->set_success(true);
        for (const auto& user_it: users_list) {
            auto user_info = response->add_friend_list();
            user_info->CopyFrom(user_it.second);
        }
    }

    virtual void FriendRemove(::google::protobuf::RpcController* controller,
                        const ::suye::FriendRemoveReq* request,
                        ::suye::FriendRemoveRsp* response,
                        ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);

        auto err_response = [this, response](const std::string& rid, 
            const std::string& errmsg) -> void {
                response->set_request_id(rid);
                response->set_success(false);
                response->set_errmsg(errmsg);
                return;
            };

        // 1.取出请求中的删除者ID和被删除者ID
        std::string rid = request->request_id();
        std::string uid = request->user_id();
        std::string pid = request->peer_id();

        // 2.从用户好友关系表中删除相关关系数据，从会话表中删除单聊会话，从会话成员表中删除会话成员信息
        bool res = _mysql_relation->remove(uid, pid);
        if (res == false) {
            LOG_ERROR("{} - 从数据库删除好友信息失败！", rid);
            return err_response(rid, "从数据库删除好友信息失败！");
        }
        res = _mysql_chat_session->remove(uid, pid);
        if (res == false) {
            LOG_ERROR("{} - 从数据库删除好友会话信息失败！", rid);
            return err_response(rid, "从数据库删除好友会话信息失败！");
        }

        // 3.组织响应，返回给网关  
        response->set_request_id(rid); 
        response->set_success(true);
    }

    virtual void FriendAdd(::google::protobuf::RpcController* controller,
                        const ::suye::FriendAddReq* request,
                        ::suye::FriendAddRsp* response,
                        ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);

        auto err_response = [this, response](const std::string& rid, 
            const std::string& errmsg) -> void {
                response->set_request_id(rid);
                response->set_success(false);
                response->set_errmsg(errmsg);
                return;
            };

        // 1.取出请求中的请求者ID和被请求者ID
        std::string rid = request->request_id();
        std::string uid = request->user_id();
        std::string pid = request->respondent_id();

        // 2.判断两人是否已经是好友
        bool res = _mysql_relation->exists(uid, pid);
        if (res == true) {
            LOG_ERROR("{} - 申请好友失败，{}-{}已经是好友关系", rid, uid, pid);
            return err_response(rid, "两者已经是好友关系！");
        }

        // 3.判断该用户是否已经申请过好友关系
        res = _mysql_apply->exists(uid, pid);
        if (res == true) {
            LOG_ERROR("{} - 申请好友失败，已经申请过对方好友！", rid, uid, pid);
            return err_response(rid, "已经申请过对方好友！");
        }

        // 4.向好友申请事件表中，新增申请信息
        std::string eid = uuid();
        FriendApply ev(eid, uid, pid);
        res = _mysql_apply->insert(ev);
        if (res == false) {
            LOG_ERROR("{} - 向数据库新增好友申请事件失败！", rid);
            return err_response(rid, "向数据库新增好友申请事件失败！");
        }

        // 5.组织响应，将事件ID信息响应给网关    
        response->set_request_id(rid);
        response->set_success(true);
        response->set_notify_event_id(eid);
    }

    virtual void FriendAddProcess(::google::protobuf::RpcController* controller,
                        const ::suye::FriendAddProcessReq* request,
                        ::suye::FriendAddProcessRsp* response,
                        ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);

        auto err_response = [this, response](const std::string& rid, 
            const std::string& errmsg) -> void {
                response->set_request_id(rid);
                response->set_success(false);
                response->set_errmsg(errmsg);
                return;
            };

        // 1.取出请求中的申请人ID和被申请人ID，以及处理结果
        std::string rid = request->request_id();
        std::string eid = request->notify_event_id();
        std::string pid = request->apply_user_id();     // 申请人
        std::string uid = request->user_id();           // 被申请人
        bool agree = request->agree();                  // 是否同意好友申请

        // 2.根据两人ID在申请事件表中查询判断是否存在申请事件
        bool res = _mysql_apply->exists(pid, uid);
        if (res == false) {
            LOG_ERROR("{} - 没有找到{}-{}对应的好友申请事件！", rid, pid, uid);
            return err_response(rid, "没有找到对应的好友申请事件！");
        }

        // 3.不管拒绝还是同意，删除申请事件表中的事件信息（该事件处理完毕）
        res = _mysql_apply->remove(pid, uid);
        if (res == false) {
            LOG_ERROR("{} - 从数据库删除申请事件 {}-{} 失败！", rid, pid, uid);
            return err_response(rid, "从数据库删除申请事件失败!");
        }

        // 4.若同意申请，则向用户关系表中添加好友关系数据，向会话表中新增会话信息，向会话成员表中新增成员信息
        std::string cssid;
        if (agree == true) {
            res = _mysql_relation->insert(pid, uid);
            if (res == false) {
                LOG_ERROR("{} - 新增好友关系信息-{}-{}！", rid, pid, uid);
                return err_response(rid, "新增好友关系信息!");
            }
            cssid = uuid();
            ChatSession cs(cssid, "", ChatSessionType::SINGLE);
            res = _mysql_chat_session->insert(cs);
            if (res == false) {
                LOG_ERROR("{} - 新增单聊会话信息-{}！", rid, cssid);
                return err_response(rid, "新增单聊会话信息失败!");
            }
            ChatSessionMember csm1(cssid, pid);
            ChatSessionMember csm2(cssid, uid);
            std::vector<ChatSessionMember> mlist = {csm1, csm2};
            res = _mysql_chat_session_member->append(mlist);
            if (res == false) {
                LOG_ERROR("{} - 没有找到{}-{}对应的好友申请事件！", rid, pid, uid);
                return err_response(rid, "没有找到对应的好友申请事件!");
            }
        }

        // 5.组织响应，将新生成的会话ID响应给网关 
        response->set_request_id(rid);
        response->set_success(true);
        response->set_new_session_id(cssid);  
    }

    virtual void FriendSearch(::google::protobuf::RpcController* controller,
                        const ::suye::FriendSearchReq* request,
                        ::suye::FriendSearchRsp* response,
                        ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);

        auto err_response = [this, response](const std::string& rid, 
            const std::string& errmsg) -> void {
                response->set_request_id(rid);
                response->set_success(false);
                response->set_errmsg(errmsg);
                return;
            };

        // 1.取出请求中的用户ID和搜索关键字
        std::string rid = request->request_id();
        std::string uid = request->user_id();
        std::string key = request->search_key();

        // 2.从好友关系表中取出该用户所有好友ID
        auto friends_id_list = _mysql_relation->friends(uid);

        // 3.根据关键字从ES服务器中进行用户搜索
        std::unordered_set<std::string> users_id_list;   
        friends_id_list.push_back(uid);     // 过滤自己和好友
        auto search_res = _es_user->search(key, friends_id_list);
        for (auto& it: search_res) {
            users_id_list.insert(it.user_id());
        }
        
        // 4.根据获取到的用户ID，从用户子服务器进行批量用户信息获取
        std::unordered_map<std::string, UserInfo> users_list;
        bool res = GetUserInfo(rid, users_id_list, users_list);
        if (res == false) {
            LOG_ERROR("{} - 批量获取用户信息失败!", rid);
            return err_response(rid, "批量获取用户信息失败!");
        }

        // 5.组织响应，将搜索到的用户列表响应给网关    
        response->set_request_id(rid);
        response->set_success(true);
        for (const auto& user_it: users_list) {
            auto user_info = response->add_user_info();
            user_info->CopyFrom(user_it.second);
        }
    }

    virtual void GetChatSessionList(::google::protobuf::RpcController* controller,
                        const ::suye::GetChatSessionListReq* request,
                        ::suye::GetChatSessionListRsp* response,
                        ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);

        auto err_response = [this, response](const std::string& rid, 
            const std::string& errmsg) -> void {
                response->set_request_id(rid);
                response->set_success(false);
                response->set_errmsg(errmsg);
                return;
            };

        // 1.从请求中取出用户ID
        std::string rid = request->request_id();
        std::string uid = request->user_id();

        // 2.取出好友的单聊会话列表和群聊会话列表
        auto single_chat_list = _mysql_chat_session->singleChatSession(uid);    
        auto group_chat_list = _mysql_chat_session->groupChatSession(uid); 

        // 3.从单聊会话中，取出所有的好友ID，从用户子服务获取用户信息
        std::unordered_set<std::string> users_id_list;
        for (const auto& chat: single_chat_list) {
            users_id_list.insert(chat.friend_id);
        }
        std::unordered_map<std::string, UserInfo> users_list;
        bool res = GetUserInfo(rid, users_id_list, users_list);
        if (res == false) {
            LOG_ERROR("{} - 批量获取用户信息失败!", rid);
            return err_response(rid, "批量获取用户信息失败!");
        }

        // 4.组织响应，将单聊会话数据和群聊会话数据组织到一起，响应给网关
        // ————单聊会话中，对方的昵称就是会话名称，对方的头像就是会话头像，会话类型为单聊类型
        for (const auto& s: single_chat_list) {
            auto chat_info = response->add_chat_session_info_list();
            chat_info->set_single_chat_friend_id(s.friend_id);
            chat_info->set_chat_session_id(s.chat_session_id);
            chat_info->set_chat_session_name(users_list[s.friend_id].nickname());
            chat_info->set_avatar(users_list[s.friend_id].avatar());
            MessageInfo msg;
            bool res = GetRecentMsg(rid, s.chat_session_id, msg);   // 从消息存储子服务获取会话的最后一条消息
            if (res == false) { continue; }
            chat_info->mutable_prev_message()->CopyFrom(msg);
        }
        for (const auto& g: group_chat_list) {
            auto chat_info = response->add_chat_session_info_list();
            chat_info->set_chat_session_id(g.chat_session_id);
            chat_info->set_chat_session_name(g.chat_session_name);
            MessageInfo msg;
            bool res = GetRecentMsg(rid, g.chat_session_id, msg);   // 从消息存储子服务获取会话的最后一条消息
            if (res == false) { continue; }
            chat_info->mutable_prev_message()->CopyFrom(msg);
        }
        response->set_request_id(rid);
        response->set_success(true);
    }
    
    virtual void ChatSessionCreate(::google::protobuf::RpcController* controller,
                        const ::suye::ChatSessionCreateReq* request,
                        ::suye::ChatSessionCreateRsp* response,
                        ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);

        auto err_response = [this, response](const std::string& rid, 
            const std::string& errmsg) -> void {
                response->set_request_id(rid);
                response->set_success(false);
                response->set_errmsg(errmsg);
                return;
            };

        // 1.从请求中取出用户ID与会话名称，以及会话的成员ID列表
        std::string rid = request->request_id();
        std::string uid = request->user_id();
        std::string ssname = request->chat_session_name();

        // 2.生成会话ID，并向会话表中新增会话信息数据，会话为群聊会话（单聊会话是同意好友申请的时候创建的）
        std::string cssid = uuid();
        ChatSession cs(cssid, ssname, ChatSessionType::GROUP);
        bool res = _mysql_chat_session->insert(cs);
        if (res == false) {
            LOG_ERROR("{} - 向数据库添加会话信息失败: {}", rid, ssname);
            return err_response(rid, "向数据库添加会话信息失败!");
        }

        // 3.向会话成员表中新增所有的成员信息
        std::vector<ChatSessionMember> csm_list;
        for (int i = 0; i < request->member_id_list_size(); i++) {
            ChatSessionMember csm(cssid, request->member_id_list(i));
            csm_list.push_back(csm);
        }
        res = _mysql_chat_session_member->append(csm_list);
        if (res == false) {
            LOG_ERROR("{} - 向数据库添加会话成员信息失败: {}", rid, ssname);
            return err_response(rid, "向数据库添加会话成员信息失败!");
        }

        // 4.组织响应，将组织好的会话信息响应给网关
        response->set_request_id(rid);
        response->set_success(true);
        response->mutable_chat_session_info()->set_chat_session_id(cssid);
        response->mutable_chat_session_info()->set_chat_session_name(ssname);
    }

    virtual void GetChatSessionMember(::google::protobuf::RpcController* controller,
                        const ::suye::GetChatSessionMemberReq* request,
                        ::suye::GetChatSessionMemberRsp* response,
                        ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);

        auto err_response = [this, response](const std::string& rid, 
            const std::string& errmsg) -> void {
                response->set_request_id(rid);
                response->set_success(false);
                response->set_errmsg(errmsg);
                return;
            };

        // 1.取出请求中用户ID和会话ID
        std::string rid = request->request_id();
        std::string uid = request->user_id();
        std::string cssid = request->chat_session_id();

        // 2.从数据库获取会话成员ID列表
        auto members_id_list = _mysql_chat_session_member->members(cssid);
        std::unordered_set<std::string> uid_list;
        for (const auto& id: members_id_list) {
            uid_list.insert(id);
        }

        // 3.从用户子服务批量获取用户信息
        std::unordered_map<std::string, UserInfo> users_list;
        bool res = GetUserInfo(rid, uid_list, users_list);
        if (res == false) {
            LOG_ERROR("{} - 批量获取用户信息失败!", rid);
            return err_response(rid, "批量获取用户信息失败!");
        }

        // 4.组织响应，将会话的成员用户信息列表响应给网关    
        response->set_request_id(rid);
        response->set_success(true);
        for (const auto& uit: users_list) {
            auto user_info = response->add_member_info_list();
            user_info->CopyFrom(uit.second);
        }
    }

    virtual void GetPendingFriendEventList(::google::protobuf::RpcController* controller,
                        const ::suye::GetPendingFriendEventListReq* request,
                        ::suye::GetPendingFriendEventListRsp* response,
                        ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);

        auto err_response = [this, response](const std::string& rid, 
            const std::string& errmsg) -> void {
                response->set_request_id(rid);
                response->set_success(false);
                response->set_errmsg(errmsg);
                return;
            };

        // 1.取出请求中的用户ID
        std::string rid = request->request_id();
        std::string uid = request->user_id();

        // 2.根据用户ID，从申请事件表&用户表中找到该用户所有待处理事件关联申请人用户ID列表
        auto users = _mysql_apply->applyUsers(uid);
        std::unordered_set<std::string> users_id_list;
        for (auto& id: users) {
            users_id_list.insert(id);
        }

        // 3.通过用户ID列表，批量获取申请人用户信息
        std::unordered_map<std::string, UserInfo> users_list;
        bool res = GetUserInfo(rid, users_id_list, users_list);
        if (res == false) {
            LOG_ERROR("{} - 批量获取用户信息失败!", rid);
            return err_response(rid, "批量获取用户信息失败!");
        }

        // 4.组织响应，将申请事件列表响应给网关    
        response->set_request_id(rid);
        response->set_success(true);
        for (const auto& user_it: users_list) {
            auto ev = response->add_event();
            ev->mutable_sender()->CopyFrom(user_it.second);
        }  
    }

private:
    // 从消息存储子服务获取会话的最后一条消息
    bool GetRecentMsg(const std::string& rid, 
                    const std::string& cssid,
                    MessageInfo& msg)
    {
        auto channel = _sm_channels->Choose(_message_service_name);
        if (!channel) {
            LOG_ERROR("{} - 获取消息存储子服务信道失败！", rid);
            return false;
        }
        MsgStorageService_Stub stub(channel.get());
        GetRecentMsgReq req;
        GetRecentMsgRsp rsp;
        brpc::Controller cntl;
        req.set_request_id(rid);
        req.set_chat_session_id(cssid);
        req.set_msg_count(1);
        stub.GetRecentMsg(&cntl, &req, &rsp, nullptr);
        if (cntl.Failed() == true) {
            LOG_ERROR("{} - 消息存储子服务调用失败：{}！", rid, cntl.ErrorText());
            return false;
        }
        if (rsp.success() == false) {
            LOG_ERROR("{} - 获取会话 {} 失败：{}！", rid, cssid, rsp.errmsg());
            return false;
        }
        if (rsp.msg_list_size() > 0) {
            msg.CopyFrom(rsp.msg_list(0));
            return true;
        }
        return false;
    }

    // 批量获取用户信息
    bool GetUserInfo(const std::string& rid, 
            const std::unordered_set<std::string>& uid_list,
            std::unordered_map<std::string, UserInfo>& user_list) 
    {
        auto channel = _sm_channels->Choose(_user_service_name);
        if (!channel) {
            LOG_ERROR("{} - 获取用户子服务信道失败！", rid);
            return false;
        }
        UserService_Stub stub(channel.get());
        GetMultiUserInfoReq req;
        GetMultiUserInfoRsp rsp;
        brpc::Controller cntl;
        req.set_request_id(rid);
        for (auto& id: uid_list) {
            req.add_users_id(id);
        }
        stub.GetMultiUserInfo(&cntl, &req, &rsp, nullptr);
        if (cntl.Failed() == true) {
            LOG_ERROR("{} - 用户子服务调用失败：{}！", rid, cntl.ErrorText());
            return false;
        }
        if (rsp.success() == false) {
            LOG_ERROR("{} - 批量获取用户信息失败：{}！", rid, rsp.errmsg());
            return false;
        }
        for (const auto& user_it: rsp.users_info()) {
            user_list.insert(std::make_pair(user_it.first, user_it.second));
        }
        return true;
    }

private:
    ESUser::ptr _es_user; 
    RelationTable::ptr _mysql_relation;
    FriendApplyTable::ptr _mysql_apply;
    ChatSessionTable::ptr _mysql_chat_session;
    ChatSessionMemberTable::ptr _mysql_chat_session_member;
    // rpc调用客户端相关对象
    std::string _user_service_name;
    std::string _message_service_name;
    std::shared_ptr<ServiceManager> _sm_channels;
};

class FriendServer {
public:
    using ptr = std::shared_ptr<FriendServer>;
    FriendServer(const Discovery::ptr service_discoverer, 
            const Registry::ptr& reg_client,
            const std::shared_ptr<elasticlient::Client>& es_client,
            const std::shared_ptr<odb::core::database>& mysql_client,
            const std::shared_ptr<brpc::Server>& server)
        : _service_discoverer(service_discoverer)
        , _registry_client(reg_client)
        , _es_client(es_client)
        , _mysql_client(mysql_client)
        , _rpc_server(server) {}

    ~FriendServer() {}
    
    // 搭建RPC服务器，并启动服务器
    void start()
    {
        _rpc_server->RunUntilAskedToQuit();
    }

private:
    Discovery::ptr _service_discoverer;
    Registry::ptr _registry_client;
    std::shared_ptr<elasticlient::Client> _es_client;
    std::shared_ptr<odb::core::database> _mysql_client;
    std::shared_ptr<brpc::Server> _rpc_server;
};

class FriendServerBuilder {
public:
    //构造es客户端对象
    void make_es_object(const std::vector<std::string> host_list) 
    {
        _es_client = ESClientFactory::create(host_list);
    }

    //构造mysql客户端对象
    void make_mysql_object(
        const std::string& user,
        const std::string& pswd,
        const std::string& db,
        const std::string& host,
        const std::string& cset,
        int port,
        int conn_pool_count) 
    {
        _mysql_client = ODBFactory::create(user, pswd, db, host, cset, port, conn_pool_count);
    }

    //用于构造服务发现客户端&信道管理对象
    void make_discovery_object(const std::string& reg_host,
                const std::string& base_service_name,
                const std::string& user_service_name,
                const std::string& message_service_name) 
    {
        _user_service_name = user_service_name;
        _message_service_name = message_service_name;
        _sm_channels = std::make_shared<ServiceManager>();
        _sm_channels->Declared(user_service_name);
        _sm_channels->Declared(message_service_name);
        LOG_DEBUG("设置用户子服务为需添加管理的子服务：{}", user_service_name);
        LOG_DEBUG("设置消息子服务为需添加管理的子服务：{}", message_service_name);
        auto put_cb = std::bind(&ServiceManager::OnServiceOnline, _sm_channels.get(), std::placeholders::_1, std::placeholders::_2);
        auto del_cb = std::bind(&ServiceManager::OnServiceOffline, _sm_channels.get(), std::placeholders::_1, std::placeholders::_2);
        _service_discoverer = std::make_shared<Discovery>(reg_host, base_service_name, put_cb, del_cb);
    }

    // 构造服务注册客户端对象
    void make_registry_object(const std::string& reg_host, 
                const std::string& service_name,
                const std::string& access_host)
    {
        _registry_client = std::make_shared<Registry>(reg_host);
        _registry_client->registry(service_name, access_host);
    }

    void make_rpc_server(uint16_t port, int32_t timeout, uint8_t num_threads) 
    {
        if (!_es_client) {
            LOG_ERROR("还未初始化ES搜索引擎模块！");
            abort();
        }
        if (!_mysql_client) {
            LOG_ERROR("还未初始化Mysql数据库模块！");
            abort();
        }
        if (!_sm_channels) {
            LOG_ERROR("还未初始化信道管理模块！");
            abort();
        }
        _rpc_server = std::make_shared<brpc::Server>();

        FriendServiceImpl* friend_service = new FriendServiceImpl(_es_client, _mysql_client,
                                    _sm_channels, _user_service_name, _message_service_name);
        int res = _rpc_server->AddService(friend_service, brpc::ServiceOwnership::SERVER_OWNS_SERVICE);
        if (res == -1) {
            LOG_ERROR("添加Rpc服务失败！");
            abort();
        }
        brpc::ServerOptions options;
        options.idle_timeout_sec = timeout;
        options.num_threads = num_threads;
        res = _rpc_server->Start(port,& options);
        if (res == -1) {
            LOG_ERROR("服务启动失败！");
            abort();
        }
    }

    //构造RPC服务器对象
    FriendServer::ptr build() 
    {
        if (!_service_discoverer) {
            LOG_ERROR("还未初始化服务发现模块！");
            abort();
        }
        if (!_registry_client) {
            LOG_ERROR("还未初始化服务注册模块！");
            abort();
        }
        if (!_rpc_server) {
            LOG_ERROR("还未初始化RPC服务器模块！");
            abort();
        }
        FriendServer::ptr server = std::make_shared<FriendServer>(
            _service_discoverer, _registry_client,
            _es_client, _mysql_client, _rpc_server);
        return server;
    }

private:
    Registry::ptr _registry_client;

    std::shared_ptr<elasticlient::Client> _es_client;
    std::shared_ptr<odb::core::database> _mysql_client;

    std::string _user_service_name;
    std::string _message_service_name;
    ServiceManager::ptr _sm_channels;
    Discovery::ptr _service_discoverer;

    std::shared_ptr<brpc::Server> _rpc_server;
};
}